package sol.leetcode;

import java.util.*;

/**
 * Intersection of Two Arrays II
 */
public class Issue350 {
    public static int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        List<Integer> res = new ArrayList<Integer>();
        for (Integer num : nums1) {
            Integer cnt = map.get(num);
            map.put(num, cnt == null ? 1 : cnt + 1);
        }
        for (Integer num : nums2) {
            Integer cnt = map.get(num);
            if (cnt == null)
                continue;
            res.add(num);
            cnt--;
            if (cnt == 0)
                map.remove(num);
            else
                map.put(num, cnt);
        }

        int[] resArr = new int[res.size()];
        for (int i = 0; i < resArr.length; ++i)
            resArr[i] = res.get(i);

        return resArr;
    }

    public static void main(String[] args) {
        int[] nums1 = {1, 2, 2, 1};
        int[] nums2 = {2, 2};
        System.out.println(Arrays.toString(intersect(nums1,nums2)));
    }
}
